package com.domain.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.domain.mapper.IRoleMapper;
import com.domain.model.Sysrole;
import com.domain.model.Sysrolenode;
/**
 * 角色权限管理 Service
 * @author wenkai
 * @since 2015年4月20日 
 */
@Service(value="roleService") 
public class RoleService {
	@Resource
	private IRoleMapper roleMapper;
	
	/**
	 * 添加一个新角色
	 * @param role
	 */
	public void doAdd(Sysrole role) {
		roleMapper.doAdd(role);
	}

	/**
	 * 查询全部角色列表
	 * @return 角色列表
	 */
	public List<Sysrole> doRoleList(){
		List<Sysrole> roles = roleMapper.doRoleList();
		return roles;
	}
	
	/**
	 * 根据编号查询单个角色
	 * @param id
	 * @return
	 */
	public Sysrole getRoleById(Long id){
		
		Sysrole role = roleMapper.getRoleById(id);
		return role;
	}
	
	/**
	 * 修改单个角色信息
	 * @param role
	 */
	public void editRole(Sysrole role){
		roleMapper.editRole(role);
	}
	
	/**
	 * 获取权限列表
	 * @param id
	 * @return
	 */
	public List<Map<String,Object>> getRightByRoleid(Long id){
		return roleMapper.getRightByRoleid(id);
	}
	
	@Transactional(rollbackFor=Exception.class)
	public void doRightSet(Long id ,String nodeIds){
		roleMapper.doDelNodeByRoleId(id);
		String[] nodes = nodeIds.split(",");
		if (nodes != null && nodes.length > 0) {
			String nodeStr;
			Sysrolenode rolenode;
			Map<String, Object> map;
			for (int i = 0; i < nodes.length; i++) {
				nodeStr = nodes[i].toString().trim();
				while (nodeStr.length()>=2) {
					map = new HashMap<>();
					map.put("roleId", id);
					map.put("nodeId", nodeStr);
					long len = roleMapper.getNoderoleidByNodeid(map) ;
					if (len == 0) {
						rolenode = new Sysrolenode();
						rolenode.setRoleId(id);
						rolenode.setNodeId(Long.valueOf(nodeStr));
						roleMapper.doAddSysrolenode(rolenode);
					}
					nodeStr = nodeStr.substring(0, nodeStr.length()-2);
				}
				
				
			}
		}
	}
	
	/**
	 * 获取左侧菜单
	 * @param id
	 * @return
	 */
	public List<Map<String,Object>> getMenuByRoleid(Long id){
		return roleMapper.getMenuByRoleid(id);
	}
	
}
